%This file generates a case of a 20x20 Cov-matrix with up to 10 sub blocks.
%sampled sequences with different levels of noice are generated and used 
%as estimated subblocks. The performance is measured for different number 
%of blocks and different noise levels. Sample length is fixed to 5000.

clear, close all
NumOfStocks = 20;
load data_10_blocks.mat
iter=0;
error=zeros(2,10);

for NumOfBlocks=3:5:8
iter=iter+1;
NoiseLevels=ones(NumOfBlocks,1);
CovBlockstemp=CovBlocks(1:NumOfBlocks);
Combinationstemp=Combinations(1:NumOfBlocks);
CovBlocksNoisy=cell(10);

for i=1:10 
CovBlocksNoisy{i} = addNoise(0.5*i*NoiseLevels, CovBlockstemp);
end

for iterNoise=1:10
        CovBlocksIter=CovBlocksNoisy{iterNoise};
    
    
    %Generate the optimal estimate
     cvx_begin
        cvx_quiet(true); 
        variable Sigma_hat(NumOfStocks, NumOfStocks) symmetric;

        %Define objective function
        f = 0;
        for q=1:NumOfBlocks
            f = f +norm(Sigma_hat(Combinationstemp{q}, Combinationstemp{q})-CovBlocksIter{q},'fro');           
        end
        minimize (f)

        subject to

        Sigma_hat == semidefinite(NumOfStocks)
                
    cvx_end
    iter
    %Compare estimate to original matrix
    error(iter, iterNoise)=norm(Sigma-Sigma_hat,'fro')
end
end

figure(1)
hold on
plot(error(1,:),'.-k')
plot(error(2,:),'--k')
title('Effect of noise on estimation')
xlabel('Level of noise')
ylabel('||S-Shat|| _f')
legend('3 sub blocks', '8 sub blocks')
